package com.kk.netty.nio;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

@Slf4j
public class ChannelDemo1 {
    //
    public static void main(String[] args) {
        /**
         * try () 1.7的语法糖，方便关闭 RandomAccessFile 资源
         * FileChannel
         * 1、输入输出流，RandomAccessFile
         */
        try (RandomAccessFile file = new RandomAccessFile ("boot_netty/helloword/data.txt", "rw")) {
            FileChannel channel = file.getChannel ( );
            ByteBuffer buffer = ByteBuffer.allocate (10);
            do {
                // 准备缓冲区，向 buffer 写入
                int len = channel.read (buffer);
                log.debug ("读到字节数：{}", len);
                if (len == -1) {// 没有内容了
                    break;
                }
                // 切换 buffer 读模式
                // 翻转缓冲区，为写做准备
                buffer.flip ( );
                while (buffer.hasRemaining ( )) {// 是否还有剩余未读数据
                    byte b = buffer.get ( );
                    log.debug ("{}", (char) b);
                }
                // 切换 buffer 写模式
                // 清楚缓冲区，为读做准备
                buffer.clear ( );
            } while (true);
        } catch (IOException e) {
            e.printStackTrace ( );
        }
    }

}
